package com.example.stuwork.service.impl;

import com.example.stuwork.common.Result;
import com.example.stuwork.dao.QuizDao;
import com.example.stuwork.dao.QuizQuestionDao;
import com.example.stuwork.dao.QuizSubmissionDao;
import com.example.stuwork.pojo.Quiz;
import com.example.stuwork.pojo.QuizQuestion;
import com.example.stuwork.pojo.QuizSubmission;
import com.example.stuwork.service.QuizQuestionService;
import com.example.stuwork.service.QuizService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 随堂测试服务实现类
 */
@Service
public class QuizServiceImpl implements QuizService {

    @Autowired
    private QuizDao quizDao;
    
    @Autowired
    private QuizQuestionDao quizQuestionDao;
    
    @Autowired
    private QuizSubmissionDao quizSubmissionDao;
    
    @Autowired
    private QuizQuestionService quizQuestionService;
    
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public Result<List<Quiz>> getQuizList() {
        try {
            List<Quiz> quizList = quizDao.findAll();
            return Result.success(quizList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取测试列表失败");
        }
    }

    @Override
    public Result<Quiz> getQuizById(Long quizId) {
        try {
            Quiz quiz = quizDao.getById(quizId);
            if (quiz == null) {
                return Result.error("测试不存在");
            }
            return Result.success(quiz);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取测试信息失败");
        }
    }

    @Override
    public Result<List<Quiz>> getQuizByCourseAndClass(String courseId, Long classId) {
        try {
            List<Quiz> quizList = quizDao.findByCourseIdAndClassId(courseId, classId);
            return Result.success(quizList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取课程班级测试列表失败");
        }
    }

    @Override
    public Result<List<Quiz>> getQuizByTeacher(String teacherId) {
        try {
            List<Quiz> quizList = quizDao.findByTeacherId(teacherId);
            return Result.success(quizList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取教师测试列表失败");
        }
    }

    @Override
    @Transactional
    public Result<?> createQuiz(Quiz quiz, String questions) {
        try {
            // 1. 插入测试基本信息
            quiz.setStatus(0); // 默认状态为未开始
            int result = quizDao.insert(quiz);
            if (result <= 0) {
                return Result.error("创建测试失败");
            }
            
            // 2. 解析并插入题目
            if (questions != null && !questions.isEmpty()) {
                List<QuizQuestion> questionList = objectMapper.readValue(questions, 
                    new TypeReference<List<QuizQuestion>>() {});
                
                for (QuizQuestion question : questionList) {
                    question.setQuizId(quiz.getQuizId());
                }
                
                int batchResult = quizQuestionDao.batchInsert(questionList);
                if (batchResult <= 0) {
                    throw new RuntimeException("添加测试题目失败");
                }
            }
            
            return Result.success("创建测试成功");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return Result.error("解析题目数据失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建测试失败: " + e.getMessage());
        }
    }

    @Override
    public Result<?> updateQuiz(Quiz quiz) {
        try {
            int result = quizDao.update(quiz);
            if (result > 0) {
                return Result.success("更新测试成功");
            } else {
                return Result.error("更新测试失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新测试失败");
        }
    }

    @Override
    @Transactional
    public Result<?> deleteQuiz(Long quizId) {
        try {
            // 1. 删除所有相关题目
            quizQuestionDao.deleteByQuizId(quizId);
            
            // 2. 删除所有相关提交记录
            quizSubmissionDao.deleteByQuizId(quizId);
            
            // 3. 删除测试记录
            int result = quizDao.deleteById(quizId);
            if (result > 0) {
                return Result.success("删除测试成功");
            } else {
                return Result.error("删除测试失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除测试失败");
        }
    }

    @Override
    public Result<Map<String, Object>> getQuizDetail(Long quizId) {
        try {
            // 获取测试基本信息
            Map<String, Object> quizDetail = quizDao.getQuizDetailById(quizId);
            if (quizDetail == null) {
                return Result.error("测试不存在");
            }
            
            // 获取测试题目列表
            List<QuizQuestion> questions = quizQuestionDao.findByQuizId(quizId);
            quizDetail.put("questions", questions);
            
            // 获取测试统计信息
            Map<String, Object> stats = quizSubmissionDao.getQuizSubmissionStats(quizId);
            if (stats != null) {
                quizDetail.putAll(stats);
            }
            
            return Result.success(quizDetail);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取测试详情失败");
        }
    }

    @Override
    public Result<?> startQuiz(Long quizId) {
        try {
            int result = quizDao.updateStatus(quizId, 1); // 更新状态为进行中
            if (result > 0) {
                return Result.success("开始测试成功");
            } else {
                return Result.error("开始测试失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("开始测试失败");
        }
    }

    @Override
    public Result<?> endQuiz(Long quizId) {
        try {
            int result = quizDao.updateStatus(quizId, 2); // 更新状态为已结束
            if (result > 0) {
                return Result.success("结束测试成功");
            } else {
                return Result.error("结束测试失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("结束测试失败");
        }
    }

    @Override
    public Result<List<Map<String, Object>>> getStudentQuizList(String courseId, Long classId, String studentId) {
        try {
            // 获取课程班级的所有测试
            List<Quiz> quizList = quizDao.findByCourseIdAndClassId(courseId, classId);
            
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Quiz quiz : quizList) {
                Map<String, Object> quizMap = new HashMap<>();
                quizMap.put("quizId", quiz.getQuizId());
                quizMap.put("title", quiz.getTitle());
                quizMap.put("description", quiz.getDescription());
                quizMap.put("status", quiz.getStatus());
                quizMap.put("createTime", quiz.getCreateTime());
                
                // 判断学生是否已提交
                boolean isSubmitted = quizSubmissionDao.isSubmitted(quiz.getQuizId(), studentId);
                quizMap.put("submitted", isSubmitted);
                
                // 如果已提交，获取得分
                if (isSubmitted) {
                    QuizSubmission submission = quizSubmissionDao.findByQuizIdAndStudentId(quiz.getQuizId(), studentId);
                    if (submission != null) {
                        quizMap.put("score", submission.getScore());
                        quizMap.put("submitTime", submission.getSubmitTime());
                    }
                }
                
                resultList.add(quizMap);
            }
            
            return Result.success(resultList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取学生测试列表失败");
        }
    }
} 